<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>上传文件框</title>
		<style>
			.file{
        display:inline-block;
        position:relative;
        overflow:hidden;
    }
    .file button{
        border-radius:3px;
        border:1px solid #ccc;
        display:inline-block;
        padding:7px 15px;
        background-color:#fff;
        cursor:pointer;
        outline:none;
    }
    .file .ycbn{
        margin-left: 8px;
    }
    .file img{
        width: 150px;
        height: 150px;
        margin: 0 auto;
        display: block;
    }
    .file input[type="file"]{
        position:absolute;
        top:-999em;
        visibility:hidden;
    }

    </style>
	</head>
	<body>
		<input type="file" title="上传图片">
		<input type="file">
		<script>
			var inps = document.querySelectorAll('input[type="file"]');
			inps.forEach(function(inp) {
				var Div = document.createElement('div');
				Div.className = 'file';
				inp.parentNode.insertBefore(Div, inp)
				var Button = document.createElement('button');
				// 三元判断
				// Button.innerHTML=inp.title?inp.title:"上传文件";
				// 短路判断
				Button.innerHTML = inp.title || "上传文件";
				var img = document.createElement('img');
				img.src = "images/1.gif";
				var btn2 = document.createElement('button');
				btn2.className = "ycbn";
				btn2.innerText = "移除";
				Div.appendChild(img);
				Div.appendChild(Button);
				Div.appendChild(inp);
				Div.appendChild(btn2);
				Button.onclick = function() {
					inp.click();
				}
				inp.onchange = function() {
					var gs = this.files[0].name.split(".").pop().toLowerCase();
					if (gs != "jpg" && gs != "png" && gs != "gif") {
						alert("请上传.jpg，.png，.gif格式文件");
						return false;
					}
					if (this.files[0].size >= 1024 * 1024 * 0.05) {
						alert("请上传小50kb的文件");
						this.value = "";
						return false;
					} else {
						//预览图片编码并显示
						var reader = new FileReader();
						reader.onloadend = function(e) {
							img.src = e.target.result;
						}
						reader.readAsDataURL(this.files[0]);
						console.log("上传成功");
					}
				}
				//移除
				btn2.onclick = function() {
					inp.value = "";
					img.src = "images/1.gif";
				}
			})

			// document.getElementsByTagName("input")[0].onchange=function(){
			//  console.log(this.files[0]);
			// }
		</script>
	</body>
</html>
